﻿package PinballCode {
	
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.display.MovieClip;
	import PinballCode.Screens.*;
	//import PinballCode.Art.Game;
	
	import com.as3toolkit.ui.Keyboarder;
	
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.events.UncaughtErrorEvent;
	
	
	// MainApp that starts the game
	public class MainApp extends MovieClip{

		//Attributes
		//private var game:Game;				
		private var currentScreen:Screen;		// current screen being viewed
		private var kb:Keyboarder; 				// keyboard listener
		private var screensList:Array;			// list of screens
		
		//XML Var
		private var xmlLoader:URLLoader = new URLLoader(); // XML Loader 
		private var xmlFile:String = "input.xml";          // file location (relative to our place)
		public var xmlData:XML;                				 // XML object to store game data
		
		//Constructor
		public function MainApp()
		{
			init();	
		}
		
		// Creates all the screens
		public function createScreens() {
			screensList = new Array();
			
			var tempScreen:Screen;	// tempScreen to be used
			
			tempScreen = new Game(this);			
			screensList.push(tempScreen);
			//addChild(currentScreen);
			
			tempScreen = new CreditScreen(this);
			screensList.push(tempScreen);
			//addChild(currentScreen);
			
			tempScreen = new InstructionsScreen(this);
			screensList.push(tempScreen);
			//addChild(currentScreen);
			
			tempScreen = new MainMenu(this);
			screensList.push(tempScreen);
		}
										
		// Initiatalizes the mainapp
		public function init()
		{
			kb = new Keyboarder(this);
			xmlLoader.addEventListener(Event.COMPLETE, loadXML);
			xmlLoader.load(new URLRequest(xmlFile));
			//displayScreen(Game);
		}
		
		// load xml daya
		private function loadXML(e:Event):void {
			xmlData = new XML(e.target.data); // set up XML object
			createScreens();
			displayScreen(MainMenu);
		}
		
		/////////////////
		//Passes in a screen.  Displays a screen if not null, and if it is null it makes a new screen to display.  If the screen is a game, it starts a new game
		////////////////////////////////
		public function displayScreen(screenClass:Class):void 
		{
			 if (currentScreen != null) 
			 {
		     	currentScreen.bringOut();				
			 }
			 
			 
				for (var i:int = 0; i < screensList.length; i++)
				{
					if(screensList[i] is screenClass)
					{
						currentScreen = screensList[i];
						currentScreen.bringIn();
						if(screensList[i] is Game)
							screensList[i].reset();
						break;						
					}
				}
			 
			
			
		}

	}
	
}
